<?php

namespace App\Http\Controllers\Lost;

use App\Exceptions\WechatException;
use App\Repository\LostRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AuditController extends Controller
{

    protected $lost;

    public function __construct(LostRepository $lost)
    {
        $this->lost = $lost;
    }

    public function canAudit()
    {
        return \Auth::guard('wechat')->user()->havePermission('lost_audit');
    }

    public function index($id)
    {
        $id = \Crypt::decrypt($id);

        $lost = $this->lost->find($id);

        $js = app('wechat')->js;

        return view('app.lost.info', compact('lost', 'js'));
    }

    public function release(Request $request)
    {
        if(!$this->canAudit()){
            throw new WechatException('你没有该权限');
        }

        $id = $request->input('id');

        $this->lost->finishLost($id);

        return $this->lost->find($id);
    }

    public function list()
    {
        return $this->lost->getPending();
    }

    public function audit(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
            'status' => 'required'
        ]);

        $result = \LostService::audit($request->input('id'), $request->input('status'));

        if(!$result){
            throw new WechatException('操作失败');
        }

        return ['code' => 200];
    }
}
